<?php

namespace App\Http\Controllers;

use App\Http\Models\City;
use Illuminate\Http\Request;

class CityController extends Controller
{
	/**
	 * Display a listing of the resource.
	 *
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function index(Request $request)
    {
			if ($request->has('limit')) {
				$items = City::paginate($request->input('limit'));
			} else {
				$items = City::all();
			}

			return $this->table($items);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
			$model = new City;
			foreach ($request->toArray() as $key => $value) {
				if (in_array($key, $model->getFillable())) {
					$model[$key] = $value;
				}
			}
			return $model->save() ?
				$this->success('') : $this->failed('添加失败');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
			return $this->success(City::find($id));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
			$model = City::find($id);
			foreach ($request->toArray() as $key => $value) {
				if (in_array($key, $model->getFillable())) {
					$model[$key] = $value;
				}
			}
			return $model->update()  ? $this->success('') : $this->failed('更新失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
			return City::where('id', $id)->delete() ? $this->success('') : $this->failed('删除失败');

		}
}
